<template>
  <div class="main" style="margin-bottom: 20px;margin-top:  20px;">
    <div>
      <el-form 
      :inline="true"
      ref="elForm"
      size="small"
      style="padding-left: 2%;"
      label-width="auto">
        <el-form-item label="在线设备">
          <el-select @change="changeDev" v-model="queryParams.mac" filterable placeholder="请选择在线设备" clearable :style="{ width: '180px' }">
            <el-option v-for="item in onlineDevList" :key="item.devMac" :label="item.devMac"
              :value="item.devMac"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="" prop="">
          <el-button
            type="primary"
            icon="el-icon-search"
            size="mini"
            @click="getDevCronList"
          >搜索
          </el-button>
          <el-button
            class="filter-item"
            type="primary"
            size="mini"
            icon="el-icon-edit"
            @click="handleCreate">
            添加
          </el-button>
          <el-button
            class="filter-item"
            type="primary"
            size="mini"
            icon="el-icon-edit"
            @click="handleAddGroupCron">
            添加设备分组任务
          </el-button>
        </el-form-item>
      </el-form>
    </div>
    <div>
      <el-table 
        :data="cronDataList"
      >
        <el-table-column type="selection" width="55" align="center" />
        <el-table-column label="任务id" prop="cronId" fixed width="60" align="center"/>
        <el-table-column label="参数设置" prop="cronParam" width="350" align="center" :show-overflow-tooltip="true" >
          <template slot-scope="scope">
            <el-tag type="success" v-if="scope.row.cronFunction == '01' && scope.row.cronParam == '01'">继电器开</el-tag>
            <el-tag type="success" v-if="scope.row.cronFunction == '01' && scope.row.cronParam == '00'">继电器关</el-tag>
            <el-tag type="info" v-if="scope.row.cronFunction == '04'">预约结束时间{{parseInt(scope.row.cronParam.substring(0, 8), 16)}}</el-tag>
            <el-tag type="info" v-if="scope.row.cronFunction == '04' && scope.row.cronParam == '00'">预约人图片编号{{scope.row.cronParam.substring(8, 10)}}</el-tag>
            <el-tag type="info" v-if="scope.row.cronFunction == '04' && scope.row.cronParam == '00'">预约设备图片编号{{scope.row.cronParam.substring(10, 12)}}</el-tag>
          </template>
        </el-table-column>
        <el-table-column label="任务开始时间" prop="cronStartDateTime" width="200" align="center" :show-overflow-tooltip="true" />
        <!-- <el-table-column label="任务结束时间" prop="cronEndDateTime" width="200" align="center" :show-overflow-tooltip="true" />    -->
        <el-table-column label="循环方式" prop="cycleType" align="center">
          <template slot-scope="scope">
            <el-tag type="info" v-if="scope.row.cycleType == 1">无限循环</el-tag>
            <el-tag type="info" v-if="scope.row.cycleType == 0">循环一次</el-tag>
          </template>
        </el-table-column>
        <!-- <el-table-column label="循环间隔" prop="cycleInterval" align="center" :show-overflow-tooltip="true" /> -->
        <el-table-column label="任务执行状态" prop="cronStatus" align="center">
          <template slot-scope="scope">
            <el-tag type="info" v-if="scope.row.cronStatus == 1">暂停</el-tag>
            <el-tag type="success" v-if="scope.row.cronStatus == 0">运行中</el-tag>
          </template>
        </el-table-column>
        <!-- <el-table-column label="任务执行次数":prop="cronRuns" align="center" :show-overflow-tooltip="true" />
        <el-table-column label="任务下次执行时间" prop="cronNextStartTime" align="center" :show-overflow-tooltip="true" />  -->
        <!-- <el-table-column label="禁用/启用" prop="cronSwitch" align="center" width="150">
          <template slot-scope="scope">
            <el-switch
              prop="cronSwitch"
              :active-value = "0"
              :inactive-value = "1"
              @change="handleStatusChange(scope.row)"
            ></el-switch>
          </template>
        </el-table-column> -->
        <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
          <template slot-scope="scope">
            <el-button
              size="mini"
              type="text"
              icon="el-icon-edit"
              @click="handleUpdate(scope.row)"
              v-hasPermi="['monitor:job:edit']"
              >修改
            </el-button>
            <el-button
              size="mini"
              type="text"
              icon="el-icon-delete"
              @click="handleDelete(scope.row)"
              v-hasPermi="['monitor:job:remove']"
              >删除
            </el-button>
          </template>
        </el-table-column>
      </el-table>
    </div>
    <el-dialog title="编辑" width="35%" :visible.sync="dialogFormVisible">
      <el-form
      :model="cronForm"
      ref="cronForm"
      :rules="rules"
      style="margin-top: 10px"
      label-width='30%'
      >
      <el-form-item label="设定执行函数" prop="cronFunction">
          <el-select v-model="cronForm.cronFunction" placeholder="请选择执行函数">
            <el-option label="开关控制" value="01"></el-option>
            <el-option label="红外控制" value="02"></el-option>
            <el-option label="预约任务" value="04"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="设定参数" prop="cronParam" v-if="cronForm.cronFunction == '01'">
          <el-select v-model="cronForm.cronParam" placeholder="请选择需设定参数">
            <el-option label="开" value="01"></el-option>
            <el-option label="关" value="00"></el-option>
          </el-select>
        </el-form-item>
        <!-- 预约任务（临时） -->
        <el-form-item label="设定参数" prop="cronParam" v-if="cronForm.cronFunction == '04'">
          <div>预约人图片编号</div>
          <el-input-number v-model="cronForm.orderImgId" :min="1" label="预约人图片编号"></el-input-number>
          <div>预约设备图片编号</div>
          <el-input-number v-model="cronForm.orderDevImgId" :min="1" label="预约设备图片编号"></el-input-number>
        </el-form-item>
        <el-form-item label="任务开始与结束时间" prop="dateTimeRange" v-if="cronForm.cronFunction != '' && cronForm.cronFunction != '02'">
          
          <el-date-picker
            v-model="cronForm.dateTimeRange"
            type="datetimerange"
            value-format="timestamp"
            range-separator="至"
            start-placeholder="开始时间"
            end-placeholder="结束时间"
            style="width: 100%;"
            :picker-options="pickerOptionDate">
        </el-date-picker>
        </el-form-item>
        <el-form-item label="循环方式" prop="cycleType" v-if="cronForm.cronFunction != '' && cronForm.cronFunction != '02' ">
          <el-select v-model="cronForm.cycleType" v-if="cronForm.cronFunction == '01'" placeholder="请选择循环方式">
            <el-option label="循环1次" value = "0"></el-option>
            <el-option label="无限循环" value = "1"></el-option>
          </el-select>
          <el-select v-model="cronForm.cycleType" v-if="cronForm.cronFunction == '04'" placeholder="请选择循环方式">
            <el-option label="循环1次" value = "0"></el-option>
          </el-select>
        </el-form-item>
        <!-- <el-form-item label="启用/禁用任务" prop="cronSwitch">
          <el-switch
            v-model="cronForm.cronSwitch"
            :active-value = "0"
            :inactive-value = "1"
            @change="changeSwitch(cronForm.cronSwitch)"
            >
          </el-switch>
        </el-form-item> -->
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="isGroupCron = false; dialogFormVisible = false; ">取消</el-button>
        <el-button type="primary" @click="onSubmit('cronForm')">确定</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import {getOnlineMac} from "@/api/alm/home/home";
import {getType} from "@/api/devTypeMap";
import {getDevCronList, refresh, addDevCron, editDevCron, delDevCron, addGroupCron, clearCronList} from "@/api/alm/dev-base-info/dev-cron/dev-cron";
import {getDevInfoList} from "@/api/alm/dev-debug/dev-network-manage/dev-network-manage";
export default{
  name: "Index",
  data() {
    var checkCronFunction = (rule, value, callback) => {
      if(!value) {
        return callback(new Error('请选择执行函数'))
      } else {
        return callback()
      }
    };
    return {
      onlineDevList: [],
      devInfoList: [],
      total: 0,
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        mac: null,
        devType: null,
        msgid: null,
      },
      appointments: {
        len: "06",
        cronEndDateTime: 0,
      },
      pickerOptionDate: {
        disabledDate(time) {
          return time.getTime() < Date.now() - 8.64e7;
        }
      },
      isGroupCron: false,
      cronDataList: [],
      maxCronId: 0,
      dialogFormVisible: false,
      cronForm: {
        cronId: 0,
        cronFunction: "",
        cronParam: "",
        orderImgId: 1,
        orderDevImgId: 1,
        cronStartDateTime: 0,
        cronEndDateTime: 0,
        dateTimeRange: [],
        cycleType: "",
        cycleInterval: 0,
        cronSwitch: 0,
      },
      rules: {
        cronFunction: [
          {required: true, message: '请选择执行函数', trigger: 'change'},
        ],
        // cronParam: [
        //   {required: true, message: '请选择需设定参数', trigger: 'change'},
        // ],
        dateTimeRange: [
          {required: true, message: '请选择日期时间', trigger: 'change'},
        ],
        cycleType: [
          {required: true, message: '请选择日期时间', trigger: 'change'},
        ],
      }
    }
  },
  computed: {
  },
  watch: {
  },
  created() {
    this.getOnlineDevMacList();
    this.getDevInfoList();
  },
  deactivated() {
  },
  //轮询获取缓存中任务列表
  mounted() {
    const timer = window.setInterval(() => {
      let obj = {};
      obj.mac = this.queryParams.mac
      if(obj.mac != null) {
        setTimeout(() => {
        refresh(obj).then(res => {
          if(res.data) {
            this.cronDataList = res.data
            console.log(this.cronDataList)
            //排序并记录id最大值
            this.cronDataList.sort((a, b) => a.cronId - b.cronId)
            this.maxCronId = this.cronDataList[this.cronDataList.length - 1].cronId
            this.cronDataList.forEach((item, index)=>{
              item.cronStartDateTime = this.timestampToTime(item.cronStartDateTime)
              item.cronEndDateTime = this.timestampToTime(item.cronEndDateTime)
            })
          } else {
            this.maxCronId = 0
          }
        })
        }, 0)
      }
    }, 3000)
    // 清除定时器
    this.$once('hook:beforeDestroy', () => {
      clearInterval(timer)
    })
  },
  methods: {
    //获取设备信息，查看该设备的设备类型
    getDevInfoList() {
      getDevInfoList(this.addDateRange(this.queryParams, this.dateRange)).then(response => {
        this.devInfoList = response.rows
        this.total = response.total
        this.devInfoList.forEach(element => {
          if(element.deviceId == this.queryParams.mac) {      
            this.queryParams.devType = element.devType
            // console.log(this.queryParams.devType) 
          }
        });
      });
    },
    //捕获到要新增任务，表单可见
    handleCreate() {
      if (this.$refs.cronForm !== undefined) {
        this.$refs.cronForm.resetFields()
       }
      console.log(this.maxCronId)
      this.dialogFormVisible = true
      this.queryParams.msgid = "01"
    },
    //捕获到要新增任务，表单可见
    handleAddGroupCron() {
      this.$confirm('设备分组任务需清空分组内设备所有任务, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        this.clearCronList()
        if (this.$refs.cronForm !== undefined) {
          this.$refs.cronForm.resetFields()
        }
        console.log(this.maxCronId)
        this.dialogFormVisible = true
        this.queryParams.msgid = "01"
        this.isGroupCron = true
      })
    },
    //捕获到修改
    handleUpdate(data) {
      console.log(data.cronFunction)
      this.queryParams.msgid = "03"
      this.cronForm.cronId = data.cronId
      this.cronForm.cronFunction = data.cronFunction
      this.cronForm.cronParam = data.cronParam
      this.cronForm.dateTimeRange = [new Date(data.cronStartDateTime.replace(/-/g,'/')), new Date(data.cronEndDateTime.replace(/-/g,'/'))]
      // this.cronForm.dateTimeRange[0] = new Date(data.cronStartDateTime.replace(/-/g,'/'))
      // this.cronForm.cronStartDateTime = this.dateTimeRange[0]
      // this.cronForm.dateTimeRange[1] = new Date(data.cronEndDateTime.replace(/-/g,'/'))
      // this.cronForm.cronEndDateTime = this.dateTimeRange[1]
      this.cronForm.cycleType = String(data.cycleType)
      this.cronForm.cronSwitch = data.cronSwitch
      this.dialogFormVisible = true
    },
    handleDelete(data) {
      let obj = {}
      obj.mac = this.queryParams.mac
      obj.devType = this.queryParams.devType
      obj.cronId = data.cronId
      delDevCron(obj).then((response) => {
          console.log(response)
        });
    },
    //获取在线设备列表
    getOnlineDevMacList() {
      getOnlineMac().then(res => {
        this.onlineDevList = res.data;
        if(this.onlineDevList.length > 0) {
          this.queryParams.mac = this.onlineDevList[0].devMac
        }
      })
    },
    //切换设备
    changeDev(e) {
      this.devInfoList.forEach(element => {
        if(element.deviceId == this.queryParams.mac) {           
          this.queryParams.devType = element.devType ? (element.devType).toString(16) : ''
        }
      })
    },
    //搜索获取任务列表
    getDevCronList() {
      let obj = {};
      obj.mac = this.queryParams.mac;
      obj.devType = this.queryParams.devType
      getDevCronList(obj).then(
        (response) => {
          if (response.code == 200) {
              this.$message.success("查询命令发送成功！")
          }
        }
      )
    },
    //获取设备类型别名
    getType(type) {
      return getType(type);
    },
    onSubmit(cronForm) {
      this.$refs[cronForm].validate((valid) => {
        if(this.cronForm.cronFunction != "01") this.isGroupCron = false
        if (valid) {
          let obj = {}
          //mac地址
          obj.mac = this.queryParams.mac
          //设备类型
          obj.devType = this.queryParams.devType
          //新增任务的话，任务id为最大id+1，修改的话
          if(this.queryParams.msgid == "01" && !this.isGroupCron) {
            obj.cronId = this.maxCronId + 1
          }
          if(this.queryParams.msgid == "01" && this.isGroupCron) {
            obj.cronId = 1  
          }
          if(this.queryParams.msgid == "03") {
            obj.cronId = this.cronForm.cronId
          }
          //执行函数
          obj.cronFunction = this.cronForm.cronFunction
          //任务参数
          if (obj.cronFunction != "04") {
            obj.cronParam = this.cronForm.cronParam
          }
          if (obj.cronFunction == "04") {
            // obj.cronParam = "0" + this.cronForm.orderImgId + "0" + this.cronForm.orderDevImgId
            let orderImgHexStr = this.cronForm.orderImgId.toString(16)
            if (orderImgHexStr.length % 2 == 1) {
              orderImgHexStr = "0" + orderImgHexStr
            }
            let orderDevImgIdHexStr = this.cronForm.orderDevImgId.toString(16)
            if (orderDevImgIdHexStr.length % 2 == 1) {
              orderDevImgIdHexStr = "0" + orderDevImgIdHexStr
            }
            let endTimeHexStr = this.cronForm.dateTimeRange[1] / 1000
            endTimeHexStr = endTimeHexStr.toString(16)
            while(endTimeHexStr.length % 8 != 0) {
              endTimeHexStr = "0" + endTimeHexStr
            }
            obj.cronParam = endTimeHexStr + orderImgHexStr + orderDevImgIdHexStr
          }
          //任务开始时间
          obj.cronStartDateTime = this.cronForm.dateTimeRange[0] / 1000
          //任务结束时间
          obj.cronEndDateTime = this.cronForm.dateTimeRange[1] / 1000
          //循环方式
          obj.cycleType = this.cronForm.cycleType
          //循环间隔
          obj.cycleInterval = this.cronForm.cycleInterval
          //任务开关
          obj.cronSwitch = this.cronForm.cronSwitch
          console.log(obj)
          if(this.queryParams.msgid == "01" && !this.isGroupCron) {
          console.log(obj)
          addDevCron(obj).then((response) => {
            this.dialogFormVisible = false;
              if (response.code == 200) {
                this.maxCronId++
                this.$message.success("添加命令发送成功！")
              }
            });
          }
          if(this.queryParams.msgid == "01" && this.isGroupCron) {
            console.log(obj)
            addGroupCron(obj).then((response) => {
              this.dialogFormVisible = false;
              this.isGroupCron = false;
                if (response.code == 200) {
                  this.$message.success("分组定时任务添加命令发送成功！")
              }
            });
          }
          if(this.queryParams.msgid == "03") {
            editDevCron(obj).then((response) => {
              this.dialogFormVisible = false;
                if (response.code == 200) {
                  this.$message.success("修改命令发送成功！")
              }
            });
          }
        } else {
          console.log('error submit!!');
          return false;
        }
      }) 
    },
    clearCronList() {
      let obj = {};
      obj.mac = this.queryParams.mac;
      obj.devType = this.queryParams.devType
      clearCronList(obj).then(
        (response) => {
          if (response.code == 200) {
              this.$message.success("清空命令发送成功！")
          }
        }
      )
    },
    //捕获任务开关改变的状态，但目前未启用
    changeSwitch(e) {
      console.log(this.cronForm.cronSwitch)
    },
    //年-月-日 时:分:秒
    timestampToTime(timestamp) {
      let date = new Date(timestamp * 1000) // 时间戳为10位需*1000，13位不需*1000
      let yy = date.getFullYear()
      let mm = this.addZero(date.getMonth() + 1)
      let dd = this.addZero(date.getDate())
      let hh = this.addZero(date.getHours())
      let mf = this.addZero(date.getMinutes())
      let ss = this.addZero(date.getSeconds())  
      return `${yy}-${mm}-${dd} ${hh}:${mf}:${ss}`
    },
    //判断时间小于10前面加0
    addZero(str) {
      return str < 10 ? '0' + str : str
    },
  }
}
</script>